# -- coding:utf-8 --
import random
import pymysql
import datetime
from dbutils.pooled_db import PooledDB


def get_param_list(str_err_data):
    """
    获取数据
    :param param_time_str: 日期时间
    :param v_list: 存放电压等级、电压线路数、同源标志、分列标志、停电标志

    """
    data_list = []
    dict_channel_level = {
        1: 4,
        2: 4,
        3: 5,
        4: 5
    }

    str_err_data_1 = (datetime.datetime.strptime(str_err_data, "%Y-%m-%d") + datetime.timedelta(days=-1)).strftime(
        "%Y-%m-%d")
    str_err_data_7 = (datetime.datetime.strptime(str_err_data, "%Y-%m-%d") + datetime.timedelta(days=-6)).strftime(
        "%Y-%m-%d")
    # print(str_err_data_1)
    # print(str_err_data_7)

    for i in range(4):
        channel_num = i + 1
        channel_level = dict_channel_level[channel_num]

        datetime.datetime.strptime(str_err_data, "%Y-%m-%d")

        calculate_time = '{} 23:59:00'.format(str_err_data_1)
        data_start_time = "{} 00:00:00".format(str_err_data_7)
        data_end_time = "{} 23:59:00".format(str_err_data_1)
        create_time = "{} 00:05:17".format(str_err_data)

        aa_ratio_error = round(random.uniform(0, 0.1), 8)
        bb_ratio_error = round(random.uniform(0, 0.1), 8)
        cc_ratio_error = round(random.uniform(0, 0.1), 8)

        aa_ratio_variance = round(random.uniform(0.00000001, 0.00000099), 8)
        bb_ratio_variance = round(random.uniform(0.00000001, 0.00000099), 8)
        cc_ratio_variance = round(random.uniform(0.00000001, 0.00000099), 8)

        aa_angle_error = round(random.uniform(0.1, 1.1), 8)
        bb_angle_error = round(random.uniform(0.1, 1.1), 8)
        cc_angle_error = round(random.uniform(0.1, 1.1), 8)

        aa_angle_variance = round(random.uniform(0.00000001, 0.00000099), 8)
        bb_angle_variance = round(random.uniform(0.00000001, 0.00000099), 8)
        cc_angle_variance = round(random.uniform(0.00000001, 0.00000099), 8)

        param = (channel_num, calculate_time, aa_ratio_error, bb_ratio_error, cc_ratio_error, aa_ratio_variance,
                 bb_ratio_variance, cc_ratio_variance, aa_angle_error, bb_angle_error, cc_angle_error,
                 aa_angle_variance, bb_angle_variance, cc_angle_variance, data_start_time, data_end_time, channel_level,
                 create_time)

        data_list.append(param)
    return data_list


def create_err_voltage_error(ip, str_err_data, time):
    """
    填充采集数据
    :param forward_day:提前的天数
    :param v_list:参数列表
    :param time:次数，秒钟
    :return:
    """
    if time != 0:
        POOL = PooledDB(creator=pymysql, maxconnections=6, mincached=2, maxcached=5, maxshared=3, blocking=True,
                        maxusage=None, setsession=[], ping=0, host=ip, port=3306, user='oetsky', password='Oetsky@123',
                        database='cvt_client_prod', charset='utf8')

        start_date_time = datetime.datetime.strptime(str_err_data, "%Y-%m-%d")
        end_data_time = start_date_time + datetime.timedelta(days=time)
        insert_sql = 'insert into err_voltage_error(`channel_num`, `calculate_time`, `aa_ratio_error`, ' \
                     '`bb_ratio_error`, `cc_ratio_error`, `aa_ratio_variance`, `bb_ratio_variance`, ' \
                     '`cc_ratio_variance`, `aa_angle_error`, `bb_angle_error`, `cc_angle_error`, ' \
                     '`aa_angle_variance`, `bb_angle_variance`, `cc_angle_variance`, `data_start_time`, ' \
                     '`data_end_time`, `ub_new`, `inputub`, `channel_level`, `create_time`, `calculate_status`, ' \
                     '`calculate_msg`, `ratio_varargin`, `angle_varargin`, `group_id`, `group_priority`, ' \
                     '`aa_qualitative_result`, `bb_qualitative_result`, `cc_qualitative_result`)' \
                     'value(%s, STR_TO_DATE(%s,"%%Y-%%m-%%d %%H:%%i:%%s"), %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, ' \
                     '%s, %s, STR_TO_DATE(%s,"%%Y-%%m-%%d %%H:%%i:%%s"), STR_TO_DATE(%s,"%%Y-%%m-%%d %%H:%%i:%%s"), ' \
                     '"none", "none", %s, STR_TO_DATE(%s,"%%Y-%%m-%%d %%H:%%i:%%s"), "0", "正常评估", NULL, NULL, 0, 0,' \
                     ' NULL, NULL, NULL)'

        conn = POOL.connection()
        cursor = conn.cursor()
        try:
            cursor.execute("TRUNCATE err_voltage_error;")
            print("已清空半年数据表")

            while True:
                str_err_data = start_date_time.strftime("%Y-%m-%d %H:%M:%S")
                param_list = get_param_list(str_err_data[:10])
                cursor.executemany(insert_sql, param_list)
                conn.commit()
                nid = cursor.lastrowid
                start_date_time = start_date_time + datetime.timedelta(days=1)
                # print(f'电压数据采集表自增ID========{nid}')
                if start_date_time >= end_data_time:
                    break
        except Exception as e:
            print(e)
        finally:
            cursor.close()
            conn.close()


if __name__ == '__main__':
    # ip = argv[1]
    ip = "192.168.253.113"
    # # 获取昨天的日期
    # yesterday = datetime.datetime.now() - datetime.timedelta(days=1)
    # # 转换为字符串格式的年月日
    # yes_str = yesterday.strftime('%Y-%m-%d')
    # print(yes_str)
    # create_err_voltage_error(ip, yes_str, time=2)

    # day=0 计算昨天数据
    create_err_voltage_error(ip, (datetime.datetime.now() + datetime.timedelta(days=0)).strftime('%Y-%m-%d'), time=1)
